package com.jjh.service.impl;

import com.jjh.consts.Result;
import com.jjh.mapper.TagMapper;
import com.jjh.pojo.Flavour;
import com.jjh.pojo.Tag;
import com.jjh.service.TagService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class TagServiceImpl implements TagService {


    @Resource
    private TagMapper tagMapper;

    @Override
    public Result getAll() {
        List<Tag> tags = tagMapper.getAll();
        return Result.ok(tags);
    }

    @Override
    public Result addOne(Tag tag) {
        if(ObjectUtils.isEmpty(tag)||"".equals(tag.getTag())){
            return Result.error("不能为空");
        }
        String tagName = tag.getTag().trim();
        //先查询看看有没有
        Flavour flavour1 = tagMapper.getByName(tagName);
        if(!ObjectUtils.isEmpty(flavour1)){
            return Result.error("该口味已经存在！");
        }
        //去掉空格
        tag.setTag(tagName);
        //不存在就可以添加了!
        int row =  tagMapper.insertOne(tag);
        if(row>0){
            return Result.ok("添加成功");
        }else{
            log.error("添加口味失败:{}",tag);
            return Result.error("添加失败");
        }
    }

    @Override
    public Result updateOne(Tag tag) {
        if(ObjectUtils.isEmpty(tag)||"".equals(tag.getTag())){
            return Result.error("不能为空");
        }
        String tagName = tag.getTag().trim();
        Flavour tag1 = tagMapper.getByName(tagName);
        //判断是否是其他的口味
        if(!ObjectUtils.isEmpty(tag1)&& !Objects.equals(tag1.getId(), tag.getId())){
            return Result.error("该口味已经存在！");
        }
        tag.setTag(tagName);
        //修改口味
        int row =  tagMapper.updateById(tag);
        if(row>0){
            return Result.ok("修改成功");
        }else{
            log.error("添加口味失败:{}",tag);
            return Result.error("修改失败");
        }
    }

    @Override
    public Result deleteByIds(List<Integer> ids) {

        int rows =  tagMapper.deleteByIds(ids);
        if(rows>0){
            return Result.ok("删除成功");
        }else{
            log.error("删除口味失败:{}",ids);
            return Result.error("删除失败");
        }

    }
}
